package io.gitee.zhangbinhub.acp.cloud.gateway.conf;

import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.util.StringUtils;

/**
 * @author zhangbin by 14/09/2018 13:14
 * @since JDK 11
 */
@Configuration
public class GatewayServerAutoConfiguration {
    private final WebEndpointProperties webEndpointProperties;
    private final String contextPath;

    public GatewayServerAutoConfiguration(ServerProperties serverProperties, WebEndpointProperties webEndpointProperties) {
        this.webEndpointProperties = webEndpointProperties;
        if (!StringUtils.hasText(serverProperties.getServlet().getContextPath())) {
            this.contextPath = "";
        } else {
            this.contextPath = serverProperties.getServlet().getContextPath();
        }
    }

    /**
     * http 验证策略配置
     *
     * @param http http 安全验证对象
     */
    @Bean
    public SecurityWebFilterChain actuatorSecurityFilter(ServerHttpSecurity http) {
        http.csrf(ServerHttpSecurity.CsrfSpec::disable).authorizeExchange(authorize ->
                authorize.pathMatchers(contextPath + webEndpointProperties.getBasePath()).authenticated()
                        .pathMatchers(contextPath + webEndpointProperties.getBasePath() + "/**").authenticated()
                        .anyExchange().permitAll()
        ).httpBasic(Customizer.withDefaults());
        return http.build();
    }
}
